// 导出文件
import { ElMessage } from 'element-plus';
import { Method } from 'axios';
import request from '/@/utils/http/axios/requestExport';

const downloadFile = function (res: any) {
  const filename =
    'content-disposition' in res.headers
      ? decodeURIComponent(
          res.headers['content-disposition'].split(';')[1].split('=')[1].replace(/"/g, ''),
        )
      : '下载文件';
  try {
    if (window.navigator?.msSaveOrOpenBlob) {
      navigator.msSaveBlob(res.data, filename);
    } else {
      const blob = new Blob([res.data], {
        type: 'application/vnd.ms-excel',
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', filename);
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(url); // 释放URL 对象
      document.body.removeChild(link);
    }
  } catch (err) {
    new Error(`err: ${err}`);
  }
};

/**
 * 文件导出
 * @param {String} url 请求地址
 * @param {Object} params 请求参数
 * @param {Object} data 请求参数, body
 * @param {Method} method 请求类型 [default 'POST'] | 'GET'
 */
export function exportFile(url: string, params?: any, data?: any, method: Method = 'POST') {
  ElMessage.success('正在导出...');
  return new Promise((resolve: (reason?: any) => void, reject: (reason?: any) => void) => {
    request({
      method,
      responseType: 'arraybuffer',
      url,
      data: params,
    })
      .then((res: any) => {
        if (res.data) {
          downloadFile(res);
        } else {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject({ msg: '对不起，筛选到的数据为空！' });
        }
        resolve();
      })
      .catch((error: any) => {
        console.error(error);
        reject(error);
      });
  });
}

/**
 * 文件导出
 * @param {String} url 请求地址
 * @param {Object} params 请求参数
 * @param {Object} data 请求参数, body
 * @param {Method} method 请求类型 [default 'POST'] | 'GET'
 */
export function handleDownloadFile(url: string, params?: any, data?: any, method: Method = 'POST') {
  ElMessage.success('正在下载...');
  return new Promise((resolve: (reason?: any) => void, reject: (reason?: any) => void) => {
    request({
      method,
      responseType: 'arraybuffer',
      url,
      data: params,
    })
      .then((res: any) => {
        if (res.data) {
          downloadFile(res);
        } else {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject({ msg: '对不起，筛选到的数据为空！' });
        }
        resolve();
      })
      .catch((error: any) => {
        console.error(error);
        reject(error);
      });
  });
}
